<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: create by allen.qiang
// +----------------------------------------------------------------------

/**
 * 配送站设置类
 * @package  module
 * @subpackage  base/system
 * @author   create by allen.qiang
 * @version 1.0
 */

class sysDistribution {

    /**
     *配送站列表
     */
    public function search( &$arg_array ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();
        //配送站ID
        if (isset($arg_array['distribution_id']) && quanli_is_int($arg_array['distribution_id'])) {
            $sql .= ' AND distribution_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['distribution_id'];
        }
        //配送站名称
        if (isset($arg_array['distribution_name']) && !empty($arg_array['distribution_name'])) {
            $sql .= ' AND distribution_name LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['distribution_name']) . '%';
        }
        //配送站编号
        if (isset($arg_array['distribution_code']) && !empty($arg_array['distribution_code'])) {
            $sql .= ' AND distribution_code = ?';
            $params_type .= 's';
            $params_array[] = trim($arg_array['distribution_code']);
        }

        //省id
        if (isset($arg_array['provinceid']) && is_numeric($arg_array['provinceid'])) {
            $sql .= ' AND provinceid = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['provinceid'];
        }

        //市ID
        if (isset($arg_array['cityid']) && is_numeric($arg_array['cityid'])) {
            $sql .= ' AND cityid = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['cityid'];
        }

        //区 id
        if (isset($arg_array['countyid']) && is_numeric($arg_array['countyid'])) {
            $sql .= ' AND countyid = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['countyid'];
        }

        //地图区域id
        if (isset($arg_array['areaID']) && is_numeric($arg_array['areaID'])) {
            $sql .= ' AND areaID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['areaID'];
        }

        //使用状态
        if (isset($arg_array['useFlg']) && is_numeric($arg_array['useFlg'])) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        //默认配送站
        if (isset($arg_array['is_default']) && is_numeric($arg_array['is_default'])) {
            $sql .= ' AND is_default = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['is_default'];
        }

        //网点类型
        if (isset($arg_array['distribution_type']) && is_numeric($arg_array['distribution_type'])) {
            $sql .= ' AND distribution_type = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['distribution_type'];
        }

        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM sys_distribution ' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM sys_distribution ' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'creator'     	             => $item->creator,
                    'createTime'  	             => $item->createTime,
                    'distribution_id'          => $item->distribution_id,
                    'distribution_name'        => $item->distribution_name,
                    'distribution_code'        => $item->distribution_code,
                    'principal'    	         => $item->principal,
                    'provinceid'               => $item->provinceid,
                    'cityid'    	            => $item->cityid,
                    'countyid'                 => $item->countyid,
                    'provinceName'            => $item->provinceName,
                    'cityName'    	            => $item->cityName,
                    'countyName'               => $item->countyName,
                    'address'    	            => $item->address,
                    'mobile'       	        => $item->mobile,
                    'phone'    		            => $item->phone,
                    'useFlg'      	            => $item->useFlg,
                    'longitude'		        => $item->longitude,
                    'latitude'		            => $item->latitude,
                    'd_precision'		        => $item->d_precision,
                    'distribution_type'		        => $item->distribution_type,
                    'audio'                    => G_IMAGE_URL .$item->audio

                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }

    /**
     * 添加、修改配送站
     *
     */
    public function editDistribution ( $arg_array ) {

        global $G_SHOP;

        quanli_include('module/base/common/quanliFile.class.php');

        quanli_include('module/base/system/mapAreaZoning.class.php');

        $quanliFile = new quanliFile();

        $mapAreaZoning = new mapAreaZoning();

        //检查参数

        if (!isset( $arg_array['distribution_name'],$arg_array['provinceid'],$arg_array['cityid'],$arg_array['countyid'],$arg_array['latitude'],$arg_array['longitude'],$arg_array['distribution_code'],$arg_array['mobile'],$arg_array['audio'],$arg_array['address'],$arg_array['principal'],$arg_array['phone'],$arg_array['distribution_type']) && !is_numeric($arg_array['distribution_id'])){
            return array('message'=>'参数错误','code'=> 400);
        }

        if (empty($arg_array['distribution_name']))

            return array( 'code' => 400, 'message' => '配送站名称不能为空' );

        if (empty($arg_array['distribution_code']))

            return array( 'code' => 400, 'message' => '配送站编号不能为空' );

        if (empty($arg_array['mobile']))

            return array( 'code' => 400, 'message' => '手机号码格式不正确' );

        if (empty($arg_array['phone']))

            return array( 'code' => 400, 'message' => '联系电话格式不正确' );

        if (empty($arg_array['address']))
            return array( 'code' => 400, 'message' => '配送站地址不能为空' );

        if (empty($arg_array['principal']))
            return array( 'code' => 400, 'message' => '配送站负责人不能为空' );

        if (empty($arg_array['provinceid']))
            return array( 'code' => 400, 'message' => '请选择省名' );

        if (empty($arg_array['cityid']))
            return array( 'code' => 400, 'message' => '请选择市名' );

        if (empty($arg_array['countyid']))
            return array( 'code' => 400, 'message' => '请选择区名' );

        if (empty($arg_array['distribution_type']))
            return array( 'code' => 400, 'message' => '请选择类型' );


        $creator                        = $arg_array['creator'];
        $distribution_id                = $arg_array['distribution_id'] ;
        $distribution_name              = $arg_array['distribution_name'] ;
        $distribution_code              = $arg_array['distribution_code'] ;
        $address	                    = $arg_array['address'] ;
        $mobile                         = $arg_array['mobile'] ;
        $phone                          = $arg_array['phone'] ;
        $principal                      = $arg_array['principal'] ;
        $audio                          = $arg_array['audio'] ;
        $latitude                       =$arg_array['latitude'];
        $longitude                      =$arg_array['longitude'];
        $provinceid                     =$arg_array['provinceid'];
        $cityid                         =$arg_array['cityid'];
        $countyid                       =$arg_array['countyid'];
        $provinceName                   =$arg_array['provinceName'];
        $cityName                       =$arg_array['cityName'];
        $countyName                     =$arg_array['countyName'];
        $areaID                         =$arg_array['areaID'];
        $distribution_type              =$arg_array['distribution_type'];


        try{

            $G_SHOP->DBCA->beginTransaction();

            //生成新的音频文件地址
            if ($audio) {
                $new_file_address = $quanliFile->basename_db( $audio );
            }

            //保存配送站信息
            $distribution = new entity('sys_distribution') ;
            if ($distribution_id == 0) {
                $distribution->creator = $creator;
                $distribution->useFlg = 1;
                $distribution->distribution_id = generate_seqno('seqno_distribution');
            } else {
                $distribution->distribution_id = $distribution_id;
                if (!$G_SHOP->DBCA->fetch($distribution)) {
                    throw new Exception('配送站信息没有找到', 404);
                }
            }
            $distribution->distribution_name = $distribution_name;
            $distribution->distribution_code = $distribution_code;
            $distribution->address = $address;
            $distribution->mobile = $mobile;
            $distribution->principal = $principal;
            $distribution->phone = $phone;
            $distribution->latitude = $latitude;
            $distribution->longitude = $longitude;
            $distribution->provinceid = $provinceid;
            $distribution->cityid = $cityid;
            $distribution->countyid = $countyid;
            $distribution->provinceName = $provinceName;
            $distribution->cityName = $cityName;
            $distribution->countyName = $countyName;
            $distribution->distribution_type = $distribution_type;

            if ($audio) {
                $distribution->audio = $new_file_address;
            }
            $G_SHOP->DBCA->save( $distribution ) ;

            if($distribution_id > 0){
                //删除配送站映射信息
                $delete_sql = 'DELETE FROM  sys_distribution_map_area WHERE distribution_id = ? ';
                $G_SHOP->DBCA->stmt_query($delete_sql, 'i', $distribution_id);
            }else{
                $distribution_id = $distribution->distribution_id;
            }
            //循环保存配送站映射信息
            $areaID_array = $areaID;

            foreach($areaID_array as $areaID){
                // 查询地图区域信息
                $arg_array = array(
                    'areaID' => $areaID,
                );

                $distribution_array = $mapAreaZoning->searchMapArea( $arg_array );

                if (!$distribution_array) {
                    throw new Exception('地图区域信息没有找到', 404);
                }

                $sys_distribution_map_area = new entity('sys_distribution_map_area') ;
                $sys_distribution_map_area->creator = $creator;
                $sys_distribution_map_area->areaID = $areaID;
                $sys_distribution_map_area->distribution_id = $distribution_id;

                $G_SHOP->DBCA->save( $sys_distribution_map_area ) ;

            }

            $G_SHOP->DBCA->commit();

            returnJsonData('保存成功', 200);

        }catch (Exception $e) {
            if ($e->getCode() > 0){

                $G_SHOP->DBCA->rollBack();

                returnJsonData( $e->getCode(), $e->getMessage() );
            }else {
                error_log($e->getMessage());
                returnJsonData( 500, '系统错误' );

            }
        }
    }

    /**
     * 配送站启用/禁用
     * @param $arg_array
     * @return array
     */
    public function changeDistributionTechnicianUseflg ( $arg_array ) {

        global $G_SHOP;

        if (!isset($arg_array['distribution_id'], $arg_array['flg']) || !quanli_is_int($arg_array['distribution_id']) || !in_array($arg_array['flg'], array(0,1)))
            return array( 'code' => 400, 'message' => '参数错误' );

        try {

            //查询配送员
            $distributionTechnician_obj = new entity('sys_distribution');
            $distributionTechnician_obj->distribution_id = $arg_array['distribution_id'];
            if (!$G_SHOP->DBCA->fetch($distributionTechnician_obj))
                return array( 'code' => 404, 'message' => '配送站信息没有找到' );

            if ($arg_array['flg']) {

                if ($distributionTechnician_obj->useFlg == 0) {
                    return array( 'code' => 406, 'message' => '配送站已禁用' );
                }
                $distributionTechnician_obj->useFlg = 0;

            } else {

                if ($distributionTechnician_obj->useFlg == 1) {
                    return array( 'code' => 406, 'message' => '配送站已启用' );
                }
                $distributionTechnician_obj->useFlg = 1;

            }
            $G_SHOP->DBCA->save($distributionTechnician_obj);

            if ($arg_array['flg'])
                return array( 'code' => 200, 'message' => '配送站禁用成功' );
            else
                return array( 'code' => 200, 'message' => '配送站启用成功' );

        } catch (Exception $e) {
            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }

    }

    /**
     * 删除配送站方式
     * @param array $pay_array 配送站ID数组
     * @return array
     */
    public function deleteDistribution ( $pay_array ) {

        global $G_SHOP;

        if (!isset($pay_array) || !is_array($pay_array) || empty($pay_array)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            $G_SHOP->DBCA->beginTransaction();

            foreach($pay_array as &$distribution_id) {

                if (in_array($distribution_id, array(1, 2, 3))) {
                    throw new Exception('ID[1,2,3]是系统默认的配送站<br />不可以删除', 404);
                }

                //查询配送站方式
                $pay_obj = new entity('sys_distribution');
                $pay_obj->distribution_id = $distribution_id;
                if (!$G_SHOP->DBCA->fetch($pay_obj)) {
                    throw new Exception('配送站信息没有找到', 404);
                }

                //判断配送站类型，删除相关的数据
                if ($pay_obj->type == 1) {

                    $delete_sql = 'DELETE FROM sys_distribution WHERE distribution_id = ?';
                    $G_SHOP->DBCA->stmt_query($delete_sql, 'i', $distribution_id);

                } else if ($pay_obj->type == 2) {

                    $delete_sql = 'DELETE FROM sys_distribution WHERE distribution_id = ?';
                    $G_SHOP->DBCA->stmt_query($delete_sql, 'i', $distribution_id);

                }  else if ($pay_obj->type == 3) {

                    $delete_sql = 'DELETE FROM sys_distribution WHERE distribution_id = ?';
                    $G_SHOP->DBCA->stmt_query($delete_sql, 'i', $distribution_id);

                }

                //删除配送站信息
                $G_SHOP->DBCA->delete($pay_obj);

                //删除配送站映射信息
                $delete_sql = 'DELETE FROM  sys_distribution_map_area WHERE distribution_id = ? ';
                $G_SHOP->DBCA->stmt_query($delete_sql, 'i', $distribution_id);

            }

            $G_SHOP->DBCA->commit();

            return array( 'code' => 200, 'message' => '删除配送站成功' );

        } catch ( Exception $e ) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     *配送站地图区域映射表查询
     */
    public function searchDistributionMapArea( &$arg_array ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();
        //配送站ID
        if (isset($arg_array['distribution_id']) && quanli_is_int($arg_array['distribution_id'])) {
            $sql .= ' AND distribution_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['distribution_id'];
        }
        //地图区域 id
        if (isset($arg_array['areaID']) && is_numeric($arg_array['areaID'])) {
            $sql .= ' AND areaID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['areaID'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            //查询分类信息
            $search_sql = 'SELECT * FROM sys_distribution_map_area ' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'uuid'     	             => $item->uuid,
                    'timeStamp'  	             => $item->timeStamp,
                    'creator'          => $item->creator,
                    'createTime'        => $item->createTime,
                    'distribution_id'        =>$item->distribution_id,
                    'areaID' => $item->areaID
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }

}